package com.qianxun.init.bo;

import com.qianxun.module.datasource1.admin.entity.SysUser;
import com.qianxun.module.datasource1.admin.service.SysUserService;
import com.qianxun.plugins.shiro.AbstractRealm;
import com.qianxun.plugins.shiro.LoginTypeToken;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

/**
 * 管理员授权处理
 * @author: huwei
 * @date:   2019/9/18 15:00
 * @version:  1.0.0
*/
@Service
public class AdminRealm extends AbstractRealm {
	@Lazy
	@Resource
	private SysUserService sysUserService;

	public AdminRealm(){
		super();
	}

	@Override
	protected UserInfo getUserInfo(AuthenticationToken token) {
		LoginTypeToken loginTypeToken = (LoginTypeToken) token;
		SysUser sysUser = sysUserService.getOneByUsername(loginTypeToken.getUsername());
		boolean isExistUser = sysUser != null;
		boolean isLocked = isExistUser && sysUser.getStatus() != 0;
		SimpleAuthenticationInfo simpleAuthenticationInfo = isExistUser ? new SimpleAuthenticationInfo(sysUser ,sysUser.getPassword() ,getName()) : null;
		return new UserInfo(isExistUser ,isLocked ,simpleAuthenticationInfo);
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

		if(SysUser.class.isAssignableFrom(principals.getPrimaryPrincipal().getClass())) {
			SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
			//管理员
			SysUser sysUser = (SysUser) principals.getPrimaryPrincipal();
			//获取功能角色列表，进行功能匹配
			List<String> roles = sysUserService.getFunctionRoleListByUuid(sysUser.getUuid());
			authorizationInfo.addRoles(roles);

			//权限添加
			Set<String> urls = sysUserService.getPermissionUrls(sysUser.getId());
			authorizationInfo.addStringPermissions(urls);
			return authorizationInfo;
		}
		return null;
	}
}
